package com.study.chapter07;

import com.study.entity.Event;
import com.study.chapter05.source.ClickSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;

/**
 * @Description:
 * @Author: LiuQun
 * @Date: 2022/8/4 22:55
 */
public class KeyedProcessFuncTest {
    public static void main(String[] args) throws Exception {
        //环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        env.addSource(new ClickSource())
                .keyBy(data -> true)
                // 处理时间语义，不需要分配时间戳和watermark
                //处理函数
                .process(new KeyedProcessFunction<Boolean, Event, String>() {
                    @Override
                    public void processElement(Event value, Context ctx, Collector<String> out) throws Exception {
                        long time = ctx.timerService().currentProcessingTime();
                        out.collect("数据到达，到达时间：" + new Timestamp(time));
                        // 注册一个10秒后的定时器
                        ctx.timerService().registerProcessingTimeTimer(time + 10 * 1000L);
                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                       out.collect("定时触发，触发时间："+new Timestamp(timestamp));
                    }
                })
                .print();

        env.execute();
    }
}
